package com.ai.platform.system.service.impl;

import com.ai.platform.common.util.AiPlatformUtil;
import com.ai.platform.core.constant.IConstants;
import com.ai.platform.model.dto.Input;
import com.ai.platform.model.dto.Output;
import com.ai.platform.common.util.ConvertUtil;
import com.ai.platform.model.vo.UserVo;
import com.ai.platform.core.exception.BusinessException;
import com.ai.platform.system.entity.SysUser;
import com.ai.platform.system.mapper.SysUserMapper;
import com.ai.platform.system.service.ISysUserService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.*;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author yeyingsheng
 * @since 2018-05-12
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    //@DataSource(name = DatasourceEnum.DATA_SOURCE_COMMON)
    public void getSysUserByAccount(Input input, Output output) throws BusinessException {
        UserVo userVo= ConvertUtil.mapArrayToBean(input.getInputMap(),UserVo.class);
        String account=userVo.getAccount();
        SysUser sysUser= this.selectOne(new EntityWrapper<SysUser>().eq("account",account).and().eq("status",'1'));
        output.setData(sysUser);
    }

    @Override
    public void listUser(Input input, Output output) throws BusinessException {
        //每页显示条数
        int limit =Integer.parseInt(input.getValue("limit"));
        //当前页
        int pageNow = Integer.valueOf(input.getValue("page"));
        EntityWrapper<SysUser> wrapper=new EntityWrapper<>();
        Page<SysUser> page = new Page(pageNow,limit);
        page.setTotal(this.selectCount(wrapper));
        page=this.selectPage(page,wrapper);
        output.setCount(page.getTotal());
        List<SysUser> userList=page.getRecords();
        if(!CollectionUtils.isEmpty(userList)){
            for (SysUser sysUser:userList){
                //去除密码
                sysUser.setPassword(null);
                sysUser.setSalt(null);
            }
        }
        output.setData(userList);
    }

    @Override
    public void saveUser(Input input, Output output) throws BusinessException {
        SysUser sysUser=ConvertUtil.mapArrayToBean(input.getInputMap(),SysUser.class);
        if(sysUser.getId()!=null){//修改
            SysUser oldUser=this.selectById(sysUser.getId());
            if(null==oldUser){
                AiPlatformUtil.returnMsgBuild(output,IConstants.FIELD_VALID_ERROR,"用户不存在");
                return;
            }
            sysUser.setSalt(oldUser.getSalt());
            sysUser.setAccount(oldUser.getAccount());
            sysUser.setCreateTime(oldUser.getCreateTime());
            sysUser.setStatus(oldUser.getStatus());
        }else{ //新增
            //账号校验
            if(this.selectOne(new EntityWrapper<SysUser>().eq("account",sysUser.getAccount()))!=null){
                //账号已存在
                AiPlatformUtil.returnMsgBuild(output,IConstants.FIELD_VALID_ERROR,"账号已存在");
                return;
            }
            Random random=new Random();
            sysUser.setSalt(String.valueOf(random.nextInt(5)));
            sysUser.setCreateTime(new Date());
        }
        //密码设置
        sysUser.setPassword(AiPlatformUtil.generatorPassword(sysUser.getPassword(),sysUser.getSalt()));
        if(!this.insertOrUpdate(sysUser)){
            //保存或修改失败
            AiPlatformUtil.returnMsgBuild(output,IConstants.UNKNOWN_ERROR,"保存失败");
        }
        Integer id=sysUser.getId();
        String roleIdStr=input.getValue("roleIds");
        if(!StringUtils.isEmpty(roleIdStr)) {
            //删除用户角色关联
            this.baseMapper.deleteUserRoleRelByUserId(id);
            //角色ID
            String[] roleIds = roleIdStr.split(AiPlatformUtil.SPLIT_ID);
            List<Map<String, Integer>> mapList = new ArrayList<>();
            //保存用户角色关系
            if (null != roleIds && roleIds.length > 0) {
                Map<String, Integer> map;
                for (String s : roleIds) {
                    map = new HashMap<>();
                    map.put("userId", id);
                    map.put("roleId", Integer.parseInt(s));
                    mapList.add(map);
                }
            }
            this.baseMapper.insertUserRoleRelBatch(mapList);
        }
    }

    @Override
    public void deleteUser(Input input, Output output) throws BusinessException {
        String ids=input.getValue("ids");
        List<Serializable> idList= AiPlatformUtil.strToList(ids,Integer.class);
        for(Serializable id:idList) {
            this.baseMapper.deleteUserRoleRelByUserId((Integer) id);
            this.deleteById(id);
        }
    }

}
